<template>
  <div class="page">
    <div class="topSearch">
      <div class="title"><span style="width: 3px;height: 20px;background-color:#0f79e2;margin-right: 8px"></span><span>采购订单</span>
      </div>
      <div class="search">
        <span>单名：</span>
        <el-input size="small" clearable style="width: 250px" v-model="purchaseName" placeholder="请输入采购单名"></el-input>
        <span>出库工厂：</span>
        <el-select clearable v-model="factoryId" size='small'
                   style="width:200px" placeholder="请选择">
          <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName"
                     :value='item.factoryId' />
        </el-select>
        <span v-if="showWarehouse">所属仓库：</span>
        <el-select v-if="showWarehouse" clearable v-model="areaId" size='small'
                   style="width:200px" placeholder="请选择">
          <el-option v-for="item in warehouseList" :key="item.area" :label="item.areaName" :value='item.area' />
        </el-select>
        <span>采购状态：</span>
        <el-select clearable v-model="completeStatus" size='small'
                   style="width:200px" placeholder="请选择">
          <el-option label="未完成" :value='0' />
          <el-option label="已完成" :value='1' />
        </el-select>

        <span>选择日期：</span>
        <el-date-picker
          v-model="sateValue"
          type="daterange"
          range-separator="至"
          clearable
          size="small"
          @change="selectTime"
          style="width: 250px"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button size="small" type="primary" style="width: 80px;margin-left: 20px" @click="getPurchaseList">查询
        </el-button>
        <el-button size="small" style="width: 80px;margin-left: 20px" @click="reset">重置
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-button size="small" type="primary" style="width: 100px;" v-if="showWarehouse" @click="addProduct">新增采购单
      </el-button>
      <el-table :data="purchaseData" border height="calc(100vh - 350px)"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                v-loading='loading'
                :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}">
        <el-table-column prop="orderNo" label="单号"  />
        <el-table-column prop="purchaseName" label="采购单名称" />
        <el-table-column label="采购明细" width="950px">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.purchaseList"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}"
              border
              style="width: 100%">
              <el-table-column prop="productCode" label="编码" />
              <el-table-column prop="productName" label="产品" width="150px" />
              <el-table-column prop="warehousePosition" label="库位">
                <template slot-scope="scope">
                  {{ scope.row.warehousePosition.toString() }}
                  <!--                  <span v-for="item in scope.row.warehousePosition">{{ item + "," }}</span>-->
                </template>
              </el-table-column>
              <el-table-column prop="norms" label="规格" />
              <el-table-column prop="purchaseNum" label="采购数量" />
              <!--              <el-table-column prop="productName" label="产品" width="200px" />-->
              <!--              <el-table-column prop="waitOut" label="待出库" />-->
              <el-table-column prop="factoryOutNum" label="工厂出库数量" width="110px" />
              <el-table-column prop="areaPutNum" label="到货数量" />
              <el-table-column prop="damageNum" label="报损数量" />
              <!--              <el-table-column prop="factoryProduceNum" label="单品多生产" />-->
              <!--              <el-table-column prop="hasNum" label="已补数量" />-->
              <!--              <el-table-column prop="warehousePosition" label="库位" />-->
              <el-table-column label="操作" width="130px">
                <template slot-scope="scope">
                  <el-link
                    v-if="scope.row.putInventory!==1&&authority.includes(308)"
                    @click="optionIn(scope.row)"
                    style="color: #0f79e2;width: 100px;background-color:#e7f1fc;margin-top: 10px;cursor: pointer;text-decoration: none">
                    入库
                  </el-link>
                  <el-link
                    v-if="scope.row.putInventory!==1&&authority.includes(307)"
                    @click="damageIn(scope.row,1)"
                    style="color: red;width: 100px;background-color:#ffebee;margin-top: 10px;cursor: pointer;text-decoration: none">
                    仓库报损
                  </el-link>
                  <el-link
                    v-if="scope.row.putInventory!==1&&authority.includes(309)"
                    @click="damageIn(scope.row,2)"
                    style="color: #787cfc;width: 100px;background-color:#f1f2ff;margin-top: 10px;cursor: pointer;text-decoration: none">
                    工厂报损确认
                  </el-link>
                  <div
                    style="color: #f5b330;width: 100px;background-color:#fef7ea;margin-top: 10px;cursor: default;text-decoration: none"
                    v-if="scope.row.putInventory==1">已完成
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="采购凭证">
          <template slot-scope="scope">
            <el-image v-for='(v, i) in scope.row.purchaseProofList' :key="i" style="width: 50px; height: 50px"
                      ref="preview" :src="host+v" :preview-src-list="previewImg">

            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="factoryId" label="发货工厂" width="130px">
          <template slot-scope="scope">
            <div class="warehouseTag" v-if="scope.row.factoryId===1"
                 style="border:1px solid #f5b330;background-color:#fef7ea;color:#f5b330;"><img
              src="@/assets/svg/hubei.svg" class="warehouse_icon" /><span>佛山一号工厂</span></div>
            <div class="warehouseTag" v-if="scope.row.factoryId===2"
                 style="border:1px solid #787cfc;background-color:#f1f2ff;color:#787cfc;"><img
              src="@/assets/svg/ningxiangyi.svg" class="warehouse_icon" /><span>佛山二号工厂</span></div>
            <div class="warehouseTag" v-if="scope.row.factoryId===3"
                 style="border:1px solid #497ff4;background-color:#f1f5fe;color:#497ff4;"><img
              src="@/assets/svg/guangdong.svg" class="warehouse_icon" /><span>广西一号工厂</span></div>
            <div class="warehouseTag" v-if="scope.row.factoryId===4"
                 style="border:1px solid #4dc8ee;background-color:#edf9fd;color:#4dc8ee;"><img
              src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span>侧网工厂</span></div>
            <div class="warehouseTag" v-if="scope.row.factoryId===0"
                 style="border:1px solid #00acf1;background-color:#e5f7f1;color:#00acf1;"><img
              src="@/assets/svg/yunnan.svg" class="warehouse_icon" /><span>其他</span></div>
            <div class="warehouseTag" v-if="scope.row.factoryId===5"
                 style="border:1px solid #4dc8ee;background-color:#edf9fd;color:#4dc8ee;"><img
              src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span>地柜工厂</span></div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="所属仓库">
          <template slot-scope="scope">
            <div v-if="scope.row.areaId===42">湖北仓</div>
            <div v-if="scope.row.areaId===43">宁乡壹</div>
            <div v-if="scope.row.areaId===44">广东仓</div>
            <div v-if="scope.row.areaId===45">广西仓</div>
            <div v-if="scope.row.areaId===52">贵州仓</div>
            <div v-if="scope.row.areaId===53">云南仓</div>
            <div v-if="scope.row.areaId===46">宁乡贰</div>
            <div v-if="scope.row.areaId===54">武汉仓</div>
          </template>
        </el-table-column>
        <el-table-column label="是否完成">
          <template slot-scope="scope">
            <div v-if="scope.row.completeStatus===0" style="color: tomato">未完成</div>
            <div v-if="scope.row.completeStatus===1" style="color: #00acf1">已完成</div>
          </template>
        </el-table-column>

        <el-table-column prop="placeOrderTime" label="创建时间" />
        <!--        <el-table-column prop="" label="是否入库">-->
        <!--          <template slot-scope="scope">-->
        <!--            <div style="color: red" v-if="scope.row.putStorage===0">否</div>-->
        <!--            <div v-if="scope.row.putStorage===1">是</div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link v-if="scope.row.completeStatus!==1&&authority.includes(310)" type="primary"
                     style="text-decoration: none"
                     @click="outInventory(scope.row)">工厂出库
            </el-link>
            <el-link type="success" style="text-decoration: none"
                     @click="exportPurchase(scope.row)">导出
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>
    <!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线-->

    <el-dialog
      title="新增采购单"
      :visible.sync="addDialog"
      width="60%"
      center
      :show-close="false"
      :before-close="handleClose">
      <div style="display: flex;align-items: center;margin-bottom: 30px;">
        <div style="width:80px;text-align: center;"><span style="color:red;">*</span>采购单名：</div>
        <el-input size="small" v-model="addForm.purchaseName" style="width: 36%"></el-input>
        <div style="width:80px;text-align: center;margin-left: 20px"><span style="color:red;">*</span>出库工厂：</div>
        <el-select clearable v-model="addForm.factoryId" size="small" style="width: 36%" @change="changeFactory"
                   placeholder="请选择工厂">
          <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName"
                     :value='item.factoryId' />
        </el-select>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 30px;">
        <div style="width:80px;text-align: center;"><span style="color:red;">*</span>收货仓库：</div>
        <el-select clearable v-model="addForm.areaId" size='small'
                   style="width:36%" placeholder="请选择">
          <el-option v-for="item in warehouseList" :key="item.area" :label="item.areaName" :value='item.area' />
        </el-select>
        <div style="width:80px;text-align: center;margin-left: 20px"><span style="color:red;">*</span>下单时间：</div>
        <el-date-picker
          v-model="addForm.placeOrderTime"
          type="date"
          size="small"
          style="width: 36%">
        </el-date-picker>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 50px">
        <div style="width:80px;text-align: center;margin-top: 30px">采购凭证：</div>
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in preSalesImg' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="preSalesImgList">
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      分割线-->
      <el-table :data="factoryInventoryData" border max-height="300px"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                v-loading='loading'
                :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}">
        <el-table-column prop="productName" label="产品名称" />

        <el-table-column prop="productCode" label="产品编码" width="" />
        <!--        <el-table-column prop="inventoryNum" label="工厂库存" width="80px" />-->
        <el-table-column prop="norms" label="规格" width="" />
        <!--        <el-table-column label="库位" width="120px">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-input v-model="scope.row.warehousePosition" @change="countChange" size="small"></el-input>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="purchaseNum" label="采购数量" width="">
          <template slot-scope="scope">
            <el-input-number :min="0" v-model="scope.row.purchaseNum" @change="countChange"
                             size="small"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="80px" />
        <el-table-column prop="warehouse" label="小计" width="80px">
          <template slot-scope="scope">
            {{ scope.row.TotalUnitPrice }}
          </template>
        </el-table-column>
      </el-table>
      <div style="position: absolute;right: 30px;margin-top: 10px"><span>合计：</span><span
        style="color: #0f79e2;font-size: 18px">{{ '¥' + allCount }}</span></div>

      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialog = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="出库"
      :visible.sync="optionOut"
      width="60%"
      center
      :show-close="false"
      :before-close="handleClose">
      <!--      分割线-->
      <el-table :data="outData" border max-height="300px"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                v-loading='loading'
                :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}">
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" width="" />
        <el-table-column prop="norms" label="规格" width="" />
        <el-table-column prop="purchaseNum" label="采购数量" width="" />
        <el-table-column prop="waitOut" label="待出库" width="" />
        <el-table-column prop="factoryOutNum" label="已出库" width="" />
        <el-table-column prop="factoryInventoryNum" label="工厂库存" width="" />
        <el-table-column prop="outCount" label="出库数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.outCount" :disabled="scope.row.disabled"
                      size="small" @change="changeOut(scope.row)"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;align-items: center;margin-top: 20px">
        <span style="width:50px">备注：</span>
        <el-input type="textarea" v-model="outRemark"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 50px">
        <div style="width:80px;margin-top: 30px">采购凭证：</div>
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in outImage' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="outImageList">
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="optionOut = false">取 消</el-button>
    <el-button type="primary" @click="submitOut">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="操作入库"
      :visible.sync="InInventory"
      width="30%"
      center
      :show-close="false"
      :before-close="handleClose">
      <div style="display: flex;align-items: center;margin-top: 10px">
        <span>已入库数量：</span>
        {{ alreadyIn }}
      </div>
      <div style="display: flex;align-items: center;margin-top: 10px">
        <span>库位列表：</span>
        <el-select v-model="warehousePosition" filterable multiple
                   placeholder="请选择" style="width: 350px;margin-left: 20px" size="small">
          <el-option v-for="item in positionList" :key="item"
                     :value="item"
                     :label="item">
          </el-option>
        </el-select>
      </div>
      <div style="display: flex;align-items: center;margin-top: 10px">
        <span>入库数量：</span>
        <el-input-number v-model="inCount" size="small" :min="0" :max="1000000" @change="limitIn"
                         style="width: 350px;margin-left: 20px"></el-input-number>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="InInventory = false">取 消</el-button>
    <el-button type="primary" @click="submitInInventory">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="报损"
      :visible.sync="destoryDialog"
      width="30%"
      center
      :show-close="false"
      :before-close="handleClose">
      <div style="display: flex;align-items: center;margin-top: 10px">
        <span>已入库数量：</span>
        <div style="margin-left: 5px"> {{ alreadyIn }}</div>
      </div>
      <div style="display: flex;align-items: flex-start;margin-top: 10px">
        <span>报损数量：</span>
        <el-input-number v-if="!this.destoryCount" v-model="damageNum" size="small" :min="0" :max="1000000"
                         @change="limitIn"
                         style="width: 350px;margin-left: 20px"></el-input-number>
        <span v-if="this.destoryCount">{{ destoryNum }}</span>
      </div>
      <div style="display: flex;align-items: flex-start;margin-top: 10px">
        <span>破损备注：</span>
        <el-input v-if="!this.destoryCount" v-model="damageRemark" type="textarea" size="small" :min="0" :max="1000000"
                  style="width: 350px;margin-left: 20px"></el-input>
        <span v-if="this.destoryCount">{{ damageRemark }}</span>
      </div>
      <div style="display: flex;align-items: flex-start;margin-top: 10px">
        <span>破损凭证：</span>
        <div v-if="!this.destoryCount" style="margin-left: 20px">
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in damageImg' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="damageImgList">
              </el-image>
              <div @click="deleteDestoryPic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
        <div v-if="this.destoryCount">
          <el-image v-for='(v, i) in damageImg' :key="i" style="width: 50px; height: 50px"
                    ref="preview" :src="host+v" :preview-src-list="damageImgList">

          </el-image>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="destoryDialog = false">取 消</el-button>
    <el-button type="primary" @click="submitDestory" v-if="!this.destoryCount">确 定</el-button>
    <el-button type="primary" @click="factorySubmit" v-if="this.destoryCount">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>


<script>
import axios from 'axios';
import Decimal from 'decimal.js';
import dayjs from 'dayjs';
import quinn from '../../utils/quinn';
import * as XLSX from 'xlsx-js-style';

export default {
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      outNum: "",
      pageNumber: 1,
      userId: "",
      inCount: "",
      damageNum: "",
      alreadyIn: "",
      damageRemark: "",
      destoryCount: false,
      purchaseName: "",
      destoryNum: "",
      warehousePosition: [],
      positionList: [],
      damageImg: [],
      damageImgList: [],
      disabled: false,
      destoryDialog: false,
      outPurchaseId: "",
      factoryId: "",
      areaId: "",
      startTime: "",
      endTime: "",
      productCode: "",
      outRemark: "",
      productId: "",
      totalCount: 0,
      host: this.$imgHost,
      warehouseId: "",
      factoryName: "",
      sateValue: "",
      loading: false,
      InInventory: false,
      allCount: "",
      completeStatus: "",
      addDialog: false,
      optionOut: false,
      addForm: {},
      warehouseList: [],
      outImage: [],
      outImageList: [],
      authority: [],
      outData: [],
      preSalesImg: [],
      preSalesImgList: [],
      previewImg: [],
      showWarehouse: true,
      factoryList: [],
      purchaseData: [],
      isUpdata: true,
      isPurchase: true,
      factoryInventoryData: []
    }
  },
  created() {
    const { authority = [] } = quinn.getStorage("userData") || {};
    this.authority = authority;
    let data = JSON.parse(window.localStorage.getItem('userData'));
    this.userName = data.userName
    this.userId = data.id
    if (data.id == 159) {
      this.factoryId = 1
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 1, factoryName: "佛山一号工厂" }]
    }
    if (data.id == 160) {
      this.factoryId = 2
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 2, factoryName: "佛山二号工厂" }]
    }
    if (data.id == 161) {
      this.factoryId = 3
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 3, factoryName: "广西一号工厂" }]
    }
    if (data.id == 162) {
      this.factoryId = 4
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 4, factoryName: "侧网工厂" }]
    }
    if (data.id == 163) {
      this.factoryId = 0
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 0, factoryName: "其他" }]
    }
    if (data.id == 164) {
      this.factoryId = 5
      this.loginType = 1
      this.showWarehouse = false
      this.factoryList = [{ factoryId: 5, factoryName: "地柜工厂" }]
    }
    document.addEventListener('paste', this.handlePaste)
    // const params = {
    //   pageSize: 100000,
    //   pageNumber: 1
    // }
    this.$api.factoryGetFactoryList().then(res => {
      if (![159, 160, 161, 162, 163, 164].includes(data.id)) {
        this.factoryList = res
      }
    })
    this.getPurchaseList()
  },
  methods: {
    handleChange(val) {
    },
    selectTime(val) {
      if (val) {
        this.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.startTime = ''
        this.endTime = ''
      }
    },
    handleClose() {
      this.optionOut = false
    },
    //操作入库
    optionPutInventory(val) {
      const data = {
        purchaseId: val.purchaseId,
        productCode: val.productCode
      }
      this.$api.purchasePurchaseMaterialAddInventory(data).then(res => {
        if (res === 1) {
          this.$message({ message: "操作成功", type: "success" })
          this.getPurchaseList()
        }
      })
    },
    //采购单列表
    async getPurchaseList() {
      this.loading = true
      const res1 = await this.$api.areaLedgerAreaList()
      if (![159, 160, 161, 162, 163, 164, 1].includes(this.userId)) {
        this.warehouseList = res1
        this.areaId = res1[0].area
      }
      if ([1].includes(this.userId)) {
        this.warehouseList = res1
      }
      const data = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        purchaseName: this.purchaseName,
        factoryId: this.factoryId,
        areaId: this.areaId,
        completeStatus: this.completeStatus,
        startTime: this.startTime,
        endTime: this.endTime,
        loginType: this.loginType
      }
      const res2 = await this.$api.purchaseGetPurchaseList(data)
      res2.data.forEach(el => {
        el.purchaseList.map(a => {
          if (!a.warehousePosition) {
            a.warehousePosition = []
          }
          a.waitOut = Decimal(a.purchaseNum).sub(Decimal(a.factoryOutNum)).toNumber()
          if (a.waitOut < 0) a.waitOut = 0
        })
        if (el.purchaseProof.includes(',')) {
          el.purchaseProofList = el.purchaseProof.split(',')
          el.purchaseProofList.forEach(val => {
            this.previewImg.push('https://' + val)
          })
        } else {
          el.purchaseProofList = [el.purchaseProof]
          el.purchaseProofList.forEach(val => {
            this.previewImg.push('https://' + val)
          })
        }

        this.purchaseData = res2.data
        this.totalCount = res2.total
      })
      this.loading = false
    },
    countChange() {
      this.allCount = new Decimal(0)
      this.factoryInventoryData.forEach(el => {
        if (!el.purchaseNum) {
          el.purchaseNum = 0
        }
        el.TotalUnitPrice = Decimal(el.price).mul(Decimal(el.purchaseNum));
        this.allCount = Decimal(this.allCount).plus(Decimal(el.TotalUnitPrice)).toNumber()
        // if (el.purchaseNum > el.inventoryNum) {
        //   this.$message({ message: "采购数量不能大于工厂库存" })
        // }
      })
    },
    submit() {
      if (!this.addForm.purchaseName || !this.addForm.factoryId || !this.addForm.areaId) {
        return this.$message({ message: "请检查必填项！" })
      }
      this.addForm.placeOrderTime = dayjs(this.addForm.placeOrderTime).format("YYYY-MM-DD")
      // const filteredList = this.factoryInventoryData.filter(item => item.purchaseNum !== 0 && item.warehousePosition);  //采购数量和库位必填
      const filteredList = this.factoryInventoryData.filter(item => item.purchaseNum !== 0); //采购数量必填，库位非必填
      const selectedFieldsArray = filteredList.map(product => ({
        purchaseNum: product.purchaseNum,
        productCode: product.productCode,
        unit: product.unit,
        price: product.price,
        productName: product.productName,
        warehousePosition: product.warehousePosition,
        norms: product.norms
      }));
      const data = {
        ...
          this.addForm,
        purchaseProofList: this.preSalesImg,
        purchaseList: selectedFieldsArray,
        purchaseCost: this.allCount
      }
      this.$api.purchaseAddPurchase(data).then(res => {
        if (res == 1) {
          this.$message({ message: "新增成功", type: "success" })
          this.addDialog = false
          this.getPurchaseList()
        }
      })
    },
    addProduct() {
      this.addDialog = true
      this.preSalesImg = this.$options.data.call(this).preSalesImg
      this.addForm = this.$options.data.call(this).addForm
      this.factoryInventoryData = []
    },
    handlePaste(event) {
      if (!(this.addDialog || this.optionOut || this.destoryDialog)) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
        .then(response => {
          this.preSalesImg.push(response.data.result[0]);
          this.preSalesImgList.push('https://' + response.data.result[0]);
          this.outImage.push(response.data.result[0]);
          this.outImageList.push('https://' + response.data.result[0]);
          this.damageImg.push(response.data.result[0]);
          this.damageImgList.push('https://' + response.data.result[0]);
        })
        .catch(error => {
        });
    },
    deletePic(i) {
      this.outImage.splice(i, 1)
    },
    deleteDestoryPic(i) {
      this.damageImg.splice(i, 1)
    },
    changeFactory(val) {
      this.allCount = ""
      const params = {
        factoryId: val,
        pageSize: 10000,
        pageNumber: 1
      }
      this.$api.factoryGetFactoryMaterialList(params).then(res => {
        res.data.map(item => {
          item.TotalUnitPrice = 0
          item.purchaseNum = 0
        })
        this.factoryInventoryData = res.data
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getPurchaseList()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getPurchaseList()
    },
    reset() {
      this.pageSize = 20
      this.pageNumber = 1
      this.purchaseName = ''
      this.factoryId = ''
      this.completeStatus = ''
      this.areaId = ''
      this.startTime = ''
      this.endTime = ''
      this.sateValue = ""
      this.getPurchaseList()
    },
    outInventory(row) {
      this.optionOut = true
      this.outPurchaseId = row.purchaseId
      this.$api.purchaseGetFactoryOutList({ purchaseId: row.purchaseId }).then(res => {
        res.list.map(el => {
          el.waitOut = Decimal(el.purchaseNum).sub(Decimal(el.factoryOutNum)).toNumber()
          if (el.factoryOutNum >= el.purchaseNum) {
            el.disabled = true
          }
          if (el.waitOut < 0) el.waitOut = 0
        })
        this.outRemark = res.factoryRemark
        if (res.factoryProof) {
          this.outImage = res.factoryProof
          res.factoryProof.map(el => {
            this.outImageList.push(this.host + el)
          })
        } else {
          this.outImage = []
          this.outImageList = []
        }
        this.outData = res.list
      })
    },
    changeOut(row) {
      if (row.outCount > row.factoryInventoryNum) {
        this.isUpdata = false
      } else {
        this.isUpdata = true
      }
      // if (row.factoryOutNum !== 0 && row.outCount > row.purchaseNum) {
      //   this.isPurchase = false
      // } else {
      //   this.isPurchase = true
      // }
    },
    submitOut() {
      const realOut = this.outData.filter(item => item.outCount)
      const realOutData = realOut.map(product => ({
        factoryOutNum: product.factoryOutNum,
        productCode: product.productCode,
        outCount: product.outCount,
      }));
      const data = {
        purchaseId: this.outPurchaseId,
        list: realOutData,
        factoryRemark: this.outRemark,
        factoryProof: this.outImage
      }
      if (!this.isUpdata) return this.$message({ message: "出库数量不可以大于工厂库存！" })
      // if (!this.isPurchase) return this.$message({ message: "出库数量不可以大于采购数量！" })
      this.$api.purchaseDeductionFactoryInventory(data).then(res => {
        if (res == 1) {
          this.$message({ message: "操作成功！", type: "success" })
          this.optionOut = false
          this.getPurchaseList()
        }
      })
    },
    optionIn(row) {
      this.InInventory = true
      this.outNum = row.factoryOutNum
      this.inPurchaseId = row.purchaseId
      this.inCount = 0
      this.inProductCode = row.productCode
      this.putInventoryNum = row.putInventoryNum
      this.warehousePosition = row.warehousePosition
      const params = {
        purchaseId: row.purchaseId,
        productCode: row.productCode
      }
      this.$api.purchaseGetAreaPutNum(params).then(res => {
        this.alreadyIn = res
      })
      this.$api.inventoryGetLocationName().then(res => {
        this.positionList = res
      })
    },
    async submitInInventory() {
      if (this.alreadyIn + this.inCount > this.outNum) return this.$message({ message: "入库数量不能大于工厂出库数量!" })
      const data = {
        purchaseId: this.inPurchaseId,
        productCode: this.inProductCode,
        putInventoryNum: this.inCount,
        warehousePosition: this.warehousePosition,
      }
      const res1 = await this.$api.purchasePurchaseMaterialAddInventory(data).then()
      if (res1) {
        this.$message({ message: "操作成功！", type: "success" })
      }
      this.InInventory = false
      const params = {
        purchaseId: this.inPurchaseId,
      }
      const res2 = await this.$api.purchaseInspectPurchaseCompleteStatus(params).then()
      await this.getPurchaseList()
    },
    limitIn(val) {
    },
    damageIn(row, type) {
      if (type == 1) {
        this.destoryCount = false

        this.destoryNum = 0
      } else {
        this.destoryNum = row.damageNum
        this.destoryCount = true
      }

      if (row.damageProof) {
        this.damageImg = row.damageProof
        row.damageProof.map(el => {
          this.damageImgList.push(this.host + el)
        })
      } else {
        this.damageImg = []
        this.damageImgList = []
      }
      this.damageRemark = row.damageRemark
      this.outNum = row.factoryOutNum
      this.inPurchaseId = row.purchaseId
      this.inProductCode = row.productCode
      this.destoryDialog = true
      const params = {
        purchaseId: row.purchaseId,
        productCode: row.productCode
      }
      this.$api.purchaseGetAreaPutNum(params).then(res => {
        this.alreadyIn = res
      })
    },
    submitDestory() {
      if (this.alreadyIn + this.damageNum > this.outNum) return this.$message({ message: "损坏数量不可以大于待入库数量！" })
      const data = {
        purchaseId: this.inPurchaseId,
        productCode: this.inProductCode,
        damageNum: this.damageNum,
        damageProof: this.damageImg,
        damageRemark: this.damageRemark,

      }
      this.$api.purchaseUpdateDamageNum(data).then(res => {
        if (res == 1) {
          this.$message({ message: "操作成功！", type: "success" })
          this.destoryDialog = false
          this.getPurchaseList()
        }
      })


    },
    factorySubmit() {
      const data = {
        purchaseId: this.inPurchaseId,
        productCode: this.inProductCode,
        damageNum: this.destoryNum
      }
      this.$api.purchaseUpdateDamageStatus(data).then(res => {
        if (res == 1) {
          this.$message({ message: "操作成功！", type: "success" })
          this.destoryDialog = false
          this.getPurchaseList()
        }
      })

    },

    exportPurchase(row) {
      const wb = XLSX.utils.book_new();
      let data = []
      data = [
        [`${row.purchaseName}`, "", "", "", "", "", "", ""],
        [`工厂:${row.factoryName}`, '', `仓库:${row.areaName}`, ''],
        ['编码', '产品', '库位', '规格', "采购数量", "工厂出库数", "到货数量", "报损数量"]]
      row.purchaseList.map(el => {
        data.push([el.productCode, el.productName, el.warehousePosition.toString(), el.norms, el.purchaseNum, el.factoryOutNum, el.areaPutNum, el.damageNum]);
      })
      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = [
        { wpx: 100 }, // 第一列宽度为250单位
        { wpx: 200 }, // 第二列宽度为300单位
        { wpx: 100 },  // 第三列宽度为350单位
        { wpx: 100 },
        { wpx: 100 },
        { wpx: 100 },
        { wpx: 100 },
        { wpx: 100 },
      ];
      ws["A1"].s = {
        alignment: { horizontal: 'center' },
        font: { blod: true, color: { rgb: '000000' } },
        fill: { fgColor: { rgb: 'ff6a00' } }
      }
      // ws["A2"].s = {
      //   alignment: { horizontal: 'center' },
      // }
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      ws['!merges'] = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 7 } },  // 合并第一行的 A 列到 H 列
        // { s: { r: 1, c: 0 }, e: { r: 1, c: 3 } },  // 合并第二行的 A 列到 D 列
        // { s: { r: 1, c: 4 }, e: { r: 1, c: 7 } }   // 合并第二行的 E 列到 H 列
      ];
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${row.purchaseName}${new Date().getTime()}.xlsx`;

      // 触发下载
      link.click();

      // 清理
      URL.revokeObjectURL(link.href);

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    }
  }
}


</script>
<style lang='less' scoped>
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }

}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}

.centerTable {
  margin-top: 20px;
}

.warehouseTag {
  display: flex;
  justify-content: center;
  height: 30px;
  //width: 120px;
  align-items: center;
  border-radius: 50px;
}

.warehouse_icon {
  width: 20px;
  height: 20px;
  margin-right: 3px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

</style>
